﻿namespace LeetCodeProject._0001_1000._001_100._31_40._032;

public class Solution
{
    public int LongestValidParentheses(string s)
    {
        int left = 0, right = 0, ans = 0;
        int n = s.Length;
        for (int i = 0; i < n; i++)
        {
            if (s[i] == '(')
                left++;
            else
                right++;
            if (left == right)
                ans = Math.Max(ans, right);
            else if (right > left)
                left = right = 0;
        }

        left = right = 0;
        for (int i = n - 1; i >= 0; i--)
        {
            if (s[i] == '(')
                left++;
            else
                right++;
            if (left == right)
                ans = Math.Max(ans, left);
            else if (left > right)
                left = right = 0;
        }

        return ans * 2;
    }
}